package com.jiayuge.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayuge.server.common.entity.RespBean;

import com.jiayuge.server.config.security.component.JwtTokenUtil;
import com.jiayuge.server.mapper.AdminRoleMapper;
import com.jiayuge.server.pojo.Admin;
import com.jiayuge.server.mapper.AdminMapper;
import com.jiayuge.server.pojo.AdminRole;
import com.jiayuge.server.pojo.Role;
import com.jiayuge.server.service.IAdminRoleService;
import com.jiayuge.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jiayu.Yang
 * @since 2021-11-16
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    /**
     * 功能: 登录之后返回token
     * * @param username
     *
     * @param code
     * @param password
     * @param request
     * @return {@link RespBean}
     * @Date 2021/11/16
     * @author jiayu.Yang
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        //校验验证码是否有效
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (!captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码错误");
        }
        //根据前端传回的username加载UserDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员");
        }

        //（更新security对象）
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //将当前对象放在SpringSecurity全局配置中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //根据UserDetails生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功", tokenMap);
    }

    /**
     * 功能: 根据用户名获取用户详情 查
     * * @param username
     *
     * @return {@link Admin}
     * @Date 2021/11/16
     * @author jiayu.Yang
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username).eq("enabled", true));
    }

    /**
     * 功能: 根据用户id获取角色  |  根据用户id获取角色  |  数据库: 增 | 删 | 改 | 查
     * * @param id
     *
     * @return {@link List< Role>}
     * @Date 2021/11/25
     * @author jiayu.Yang
     */
    @Override
    public List<Role> getRoles(Integer id) {
        return adminMapper.getRoles(id);
    }

    /**
     * 功能: 获取所有操作员(模糊查询)  |  获取所有操作员(模糊查询)  |  数据库: 增 | 删 | 改 | 查
     * * @param keywords
     *
     * @return {@link List< Admin>}
     * @Date 2021/11/25
     * @author jiayu.Yang
     */
    @Override
    public List<Admin> getAllAdmin(String keywords) {
        //获取当前登录用户操作员信息
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //过滤掉当前登录的操作员
        return adminMapper.getAllAdmin(admin.getId(), keywords);
    }

    /**
     * 功能: 更新操作员角色  |  更新操作员角色  |  数据库: 增 | 删 | 改 | 查
     * * @param aid
     *
     * @param rids
     * @return {@link RespBean}
     * @Date 2021/11/25
     * @author jiayu.Yang
     */
    @Override
    @Transactional
    public RespBean updateAdminRole(Integer aid, Integer[] rids) {
        //根据adminId删除原因的角色
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", aid));
        //插入对应操作员的角色
        Integer result = adminRoleMapper.addAdminRole(aid, rids);
        if (rids.length == result) {
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    /**
     * 功能: 更新用户密码  |  更新用户密码  |  数据库: 增 | 删 | 改 | 查
     * * @param oldPass
     *
     * @param pass
     * @param adminId
     * @return {@link RespBean}
     * @Date 2021/12/8
     * @author jiayu.Yang
     */
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println(encoder.encode("123"));
        //oldPass和当前要改用户的密码是否对应
        if (encoder.matches(oldPass, admin.getPassword())) {
            //设置新密码，（encode加密处理）
            admin.setPassword(encoder.encode(pass));
            int result = adminMapper.updateById(admin);
            if (result == 1){
                return RespBean.success("更新成功");
            }
        }
        return RespBean.error("更新失败");
    }
}
